
package cn.dreambug.messageQ;

import java.io.Serializable;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQObjectMessage;


public class Sender {
	
	private static Session session = null;
	private static MessageProducer producer = null;
	
	private static void initSender(){
		ConnectionFactory connectionFactory;
		Connection connection = null;
		session = null;
		Destination destination;
		producer = null;
		connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616");

		try {
			connection = connectionFactory.createConnection();
			connection.start();
			session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			destination = session.createQueue("wechat - message");
			producer = session.createProducer(destination);
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
//				if (null != connection)
//					connection.close();
			} catch (Throwable ignore) {
			}
		}

	}

	/**
	 * 发送Java类型消息
	 * @param moneyMessage
	 * @throws Exception
	 */
	public static void sendMessage(Object moneyMessage) throws Exception {
		if(session == null && producer == null){
			initSender();
		}
		ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage();
		msg.setObject((Serializable) moneyMessage);
		producer.send(msg);
		session.commit();
	}
	
}
